package yf.mall.service.impl;

import com.yf.response.RRException;
import com.yf.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yf.mall.dao.AreaDao;
import yf.mall.dao.UserDao;
import yf.mall.entity.AreaEntity;
import yf.mall.entity.UserEntity;
import yf.mall.service.AreaService;
import yf.mall.vo.AreaVo;

import java.util.List;

/**
 * 区域代理Service实现类
 *
 *
 * 
 * @date Thu May 07 14:16:15 CST 2020
 */
@Service
public class AreaServiceImpl extends BaseServiceImpl<AreaEntity> implements AreaService {

    private AreaDao areaDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    public void setDao(AreaDao areaDao) {
        this.areaDao = areaDao;
        super.setBaseDao(areaDao);
    }


    /**
     * @Override public List<UserVo> queryListVo(UserVo userVo) {
     * return userDao.queryListVo(userVo);
     * }
     * @Override public UserVo getVo(Long id) {
     * return userDao.getVo(id);
     * }
     **/
    @Override
    public List<AreaVo> queryListVo(AreaVo areaVo) {
        return areaDao.queryListVo(areaVo);
    }

    @Override
    public AreaVo getVo(Long id) {
        return areaDao.getVo(id);
    }


    /**内部方法**/


    /**外部方法实现**/

    /**
     * 判断用户存不存在以及该地区有没有代理
     *
     * @param areaVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AreaVo merge(AreaVo areaVo) {
        AreaEntity area = getEntity(areaVo);
        if (areaVo.getArea().getId()==null) {
            this.save(area);
            return areaVo;
        }
        this.update(area);
        return areaVo;
    }

    /**
     * 根据查询是否有该级别
     * @param areaVo
     * @return
     */
    private AreaEntity getEntity(AreaVo areaVo) {
        String code = areaVo.getUser().getCode();
        UserEntity user = this.userDao.findByCode(code);
        if (user == null) {
            throw new RRException("编号对应的用户不存在");
        }
        AreaEntity areaVoArea = areaVo.getArea();
        areaVoArea.setUserId(user.getId());
        AreaEntity area = this.areaDao.findByNameAndGoodsId(areaVoArea.getName(),areaVoArea.getGoodsId());
        if (area != null && !area.getId().equals(areaVoArea.getId())) {
            throw new RRException("该商品在此地区已有代理");
        }
        return areaVoArea;
    }


}
